package com.prep;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class CheckPackagesReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent a) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> list = manager.getRunningAppProcesses();
		if (list == null) {
			Log.d("prep info", "NULL");
			return;
		}
		boolean isRunning = false;
		for (RunningAppProcessInfo info : list) {
			if (info.processName.equals("com.google.android.apps.maps")) {
				isRunning = info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
				SharedPreferences preferences = context.getSharedPreferences(
						"pref", Context.MODE_PRIVATE);
				boolean wasRunning = preferences.getBoolean("isRunning",
						isRunning);
				preferences.edit().putBoolean("isRunning", isRunning).commit();
				if (wasRunning == true && isRunning == false) {
					Intent intent = new Intent(context, EnterDiaryEntry.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
					preferences.edit().putBoolean("isRunning", false).commit();
				}
				break;
			}
		}
		Log.d("prep info", "isRunning: " + isRunning);
	}

}
